package com.ymatou.iapi.sellerquery.testcase;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.query.seller.trading.api.parameter.ExistsSellerOrdersBean;
import com.ymatou.query.seller.trading.api.parameter.Seller.ExistsSellerOrdersResponse;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.common.enums.LogisticsTypeEnum;
import com.ymttest.common.enums.OrderStatusEnum;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;

/**
 * @date 2016-07-18
 * @author songyefeng
 * @desc 卖家订单是否存在
 */
@SuppressWarnings("rawtypes")
@TestSuite
public class Ts_ExistsSellerOrders {

	private static ExistsSellerOrdersBean existsSellerOrdersBean;
	private static com.ymatou.query.seller.trading.api.service.ExistsSellerOrdersCall existsSellerOrdersCall;
//	private static com.ymatou.iapi.trading.sellerquery.service.ExistsSellerOrdersCall existsSellerOrdersCall;


	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("卖家订单是否存在");
	}

	@Before
	public void caseUp() {
		existsSellerOrdersBean = new ExistsSellerOrdersBean();
		existsSellerOrdersCall = new com.ymatou.query.seller.trading.api.service.ExistsSellerOrdersCall();
//		existsSellerOrdersCall = new com.ymatou.iapi.trading.sellerquery.service.ExistsSellerOrdersCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(existsSellerOrdersCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private void verify() {
		ExistsSellerOrdersResponse expectedResponse = new ExistsSellerOrdersResponse();
		ConstructExpectedResponse(expectedResponse);
		ExistsSellerOrdersResponse actualResponse = existsSellerOrdersCall
				.getExistsSellerOrdersResponse();
		DataUtil.verifyEquals(expectedResponse.isToBeAccepted(),
				actualResponse.isToBeAccepted(), "验证ToBeAccepted");
		DataUtil.verifyEquals(expectedResponse.isToBeAppliedPostpay(),
				actualResponse.isToBeAppliedPostpay(), "验证ToBeAppliedPostpay");
		DataUtil.verifyEquals(expectedResponse.isToBeConfirmed(),
				actualResponse.isToBeConfirmed(), "验证ToBeConfirmed");
		DataUtil.verifyEquals(expectedResponse.isToBeDelivered(),
				actualResponse.isToBeDelivered(), "验证ToBeDelivered");
		DataUtil.verifyEquals(expectedResponse.isToBePaid(),
				actualResponse.isToBePaid(), "验证ToBePaid");
		DataUtil.verifyEquals(expectedResponse.isToBePostpaid(),
				actualResponse.isToBePostpaid(), "验证ToBePostpaid");
	}

	private void ConstructExpectedResponse(ExistsSellerOrdersResponse response) {
		Process(response);
	}

	private void Process(ExistsSellerOrdersResponse response) {
		StringBuffer sql = new StringBuffer();

		if (existsSellerOrdersBean.getOrderCreatedTimeBegin() == null
				&& existsSellerOrdersBean.getOrderCreatedTimeEnd() == null
				&& existsSellerOrdersBean.getOrderPaidTimeBegin() == null
				&& existsSellerOrdersBean.getOrderPaidTimeEnd() == null) {
			existsSellerOrdersBean.setOrderCreatedTimeBegin(YMTDateUtil
					.addMonths(-5,YMTDateUtil.YMDHMS));
		}

		String indexName = null;
		String cond = GetConditionAndSetArgs(indexName);

		GetStatusSQL("ToBePaid", indexName, sql,
				OrderStatusEnum.OrderEstablish.getValue(), null);
		sql.append(cond + "\n");
		sql.append("union all " + "\n");

		GetStatusSQL("ToBeAccepted", indexName, sql,
				OrderStatusEnum.AccountPaid.getValue(), null);
		sql.append(cond + "\n");
		sql.append("union all " + "\n");

		GetStatusSQL("ToBeAppliedPostpay", indexName, sql,
				OrderStatusEnum.SellerAccept.getValue(), false);
		sql.append(cond + "\n");
		sql.append("union all " + "\n");

		GetStatusSQL("ToBePostpaid", indexName, sql,
				OrderStatusEnum.ApplyForPostPay.getValue(), null);
		sql.append(cond + "\n");
		sql.append("union all " + "\n");

		GetStatusSQL("ToBeDelivered", indexName, sql,
				OrderStatusEnum.SellerAccept.getValue(), true);
		sql.append(cond + "\n");
		sql.append("union all " + "\n");

		GetStatusSQL("ToBeConfirmed", indexName, sql,
				OrderStatusEnum.Shipped.getValue(), null);
		sql.append(cond + "\n");

		List<Map> l = new DefaultWapper().executeSql(sql);
		if (!DataUtil.isNullOrEmpty(l)) {
			response.setToBeAccepted(l.stream().anyMatch(
					x -> x.containsValue("ToBeAccepted")));
			response.setToBeAppliedPostpay(l.stream().anyMatch(
					x -> x.containsValue("ToBeAppliedPostpay")));
			response.setToBeConfirmed(l.stream().anyMatch(
					x -> x.containsValue("ToBeConfirmed")));
			response.setToBeDelivered(l.stream().anyMatch(
					x -> x.containsValue("ToBeDelivered")));
			response.setToBePaid(l.stream().anyMatch(
					x -> x.containsValue("ToBePaid")));
			response.setToBePostpaid(l.stream().anyMatch(
					x -> x.containsValue("ToBePostpaid")));
		}
	}

	private static void GetStatusSQL(String name, String index,
			StringBuffer sql, int status, Boolean paidInFull) {
		sql.append("select top 1 '").append(name)
				.append("' from ymt_orders o with(nolock");
		if (!DataUtil.Stringg.IsNullOrWhiteSpace(index)) {
			sql.append("index = " + index);
		}
		sql.append(") ");

		if (!DataUtil.Stringg.IsNullOrWhiteSpace(existsSellerOrdersBean
				.getProductName())
				|| status == OrderStatusEnum.Shipped.getValue()
				&& existsSellerOrdersBean.getDomesticDelivered() != null
				&& !DataUtil.Booleann.GetValueOrDefault(existsSellerOrdersBean.getDomesticDelivered())) {
			sql.append(" join ymt_orderinfo(nolock) i on i.iorderid = o.iorderid ");
		}

		sql.append(" where ");
		sql.append(" o.itradingstatus = ").append(status).append(" ");

		if (paidInFull != null) {
			sql.append("and o.bpaidinfull = ").append(paidInFull ? 1 : 0)
					.append(" ");
		}

		if (status == OrderStatusEnum.Shipped.getValue()
				&& existsSellerOrdersBean.getDomesticDelivered() != null) {
			if (DataUtil.Booleann.GetValueOrDefault(existsSellerOrdersBean.getDomesticDelivered())) {
				sql.append(" and o.bdomesticdelivered = 1 ");
			} else {
				sql.append(" and i.iCatalogStatus = ")
						.append(LogisticsTypeEnum.PackageDelivery.getValue())
						.append(" and o.bdomesticdelivered is null ");
			}
		}
	}

	private static String GetConditionAndSetArgs(String indexName) {

		StringBuffer sql = new StringBuffer();

		sql.append(" and o.ibuyerid = " + existsSellerOrdersBean.getSellerId());

		boolean orderOrGroupIdOnly = false;
		if (existsSellerOrdersBean.getOrderId() != null) {
			sql.append(" and o.iorderid = "
					+ existsSellerOrdersBean.getOrderId());
			orderOrGroupIdOnly = true;
			indexName = "PK_Ymt_Orders";
		}

		if (existsSellerOrdersBean.getOrderGroupId() != null) {
			sql.append(" and o.imainorderid = "
					+ existsSellerOrdersBean.getOrderGroupId());
			orderOrGroupIdOnly = true;
			indexName = "IDX_Ymt_Orders_iMainOrderId";
		}
		// bool tCreated = false, tPaid = false;
		if (existsSellerOrdersBean.getOrderCreatedTimeBegin() != null) {
			sql.append(" and o.dAddTime >= '"
					+ existsSellerOrdersBean.getOrderCreatedTimeBegin() + "'");
		}
		if (existsSellerOrdersBean.getOrderCreatedTimeEnd() != null) {
			sql.append(" and o.dAddTime <= '"
					+ existsSellerOrdersBean.getOrderCreatedTimeEnd() + "'");
		}

		if (existsSellerOrdersBean.getOrderPaidTimeBegin() != null) {
			sql.append(" and ( (o.[dPostPaidTime] is null and o.[dPaidTime] >= '"
					+ existsSellerOrdersBean.getOrderPaidTimeBegin()
					+ "') or o.[dPostPaidTime] >= '"
					+ existsSellerOrdersBean.getOrderPaidTimeBegin() + "')");
		}
		if (existsSellerOrdersBean.getOrderPaidTimeEnd() != null) {
			sql.append(" and ( (o.[dPostPaidTime] is null and o.dPaidTime <= '"
					+ existsSellerOrdersBean.getOrderPaidTimeEnd()
					+ "')  or o.[dPostPaidTime] <= '"
					+ existsSellerOrdersBean.getOrderPaidTimeEnd() + "')");
		}

		if (!DataUtil.Stringg.IsNullOrWhiteSpace(existsSellerOrdersBean
				.getBuyerNickName())) {
			sql.append(" and o.sBuyerNickName = '"
					+ existsSellerOrdersBean.getBuyerNickName() + "' ");
		}

		if (!DataUtil.Stringg.IsNullOrWhiteSpace(existsSellerOrdersBean
				.getProductName())) {
			sql.append(" and i.sTitle like '%"
					+ existsSellerOrdersBean.getProductName() + "%' ");
		}

		if (existsSellerOrdersBean.getOrderRefund()) {
			sql.append(" and o.iSalesRefundStatus is not null ");
		}

		if (!orderOrGroupIdOnly) {
			indexName = "idx_Ymt_Orders_iBuyerId_iTradingStatus_bDomesticDelivered";
		}

		return sql.toString();
	}

	private static final String YMD = "yyyy-MM-dd";

	private static String calendar2YMDString(Calendar calendar) {
		return new SimpleDateFormat(YMD).format(calendar.getTime());
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_001() {
		Logger.start(true, "卖家订单是否存在,只传SellerId");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			// existsSellerOrdersBean.setProductName("测试");
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	private Calendar getNow() {
		return Calendar.getInstance();
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_002() {
		Logger.start(true,"卖家订单是否存在,只传SellerId, orderCreatedTimeBegin,orderCreatedTimeEnd");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			Calendar orderCreatedTimeBegin = getNow();
			orderCreatedTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderCreatedTimeEnd = getNow();
			orderCreatedTimeEnd.add(Calendar.MONTH, -2);
			existsSellerOrdersBean
					.setOrderCreatedTimeBegin(calendar2YMDString(orderCreatedTimeBegin));
			existsSellerOrdersBean
					.setOrderCreatedTimeEnd(calendar2YMDString(orderCreatedTimeEnd));
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_003() {
		Logger.start(true,"卖家订单是否存在,只传SellerId, orderPaidTimeBegin,orderPaidTimeEnd");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			Calendar orderPaidTimeBegin = getNow();
			orderPaidTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderPaidTimeEnd = getNow();
			orderPaidTimeEnd.add(Calendar.MONTH, -2);
			existsSellerOrdersBean
					.setOrderPaidTimeBegin(calendar2YMDString(orderPaidTimeBegin));
			existsSellerOrdersBean
					.setOrderPaidTimeEnd(calendar2YMDString(orderPaidTimeEnd));
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	@Ignore
	public void Tc_ExistsSellerOrders_004() {
		Logger.start(true,"卖家订单是否存在,只传SellerId, orderCreatedTimeBegin,orderCreatedTimeEnd,productName");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			existsSellerOrdersBean.setProductName("商品");
			Calendar orderCreatedTimeBegin = getNow();
			orderCreatedTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderCreatedTimeEnd = getNow();
			orderCreatedTimeEnd.add(Calendar.MONTH, -2);
			existsSellerOrdersBean
					.setOrderCreatedTimeBegin(calendar2YMDString(orderCreatedTimeBegin));
			existsSellerOrdersBean
					.setOrderCreatedTimeEnd(calendar2YMDString(orderCreatedTimeEnd));
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_005() {
		Logger.start(
				true,"卖家订单是否存在,只传SellerId, orderPaidTimeBegin,orderPaidTimeEnd,domesticDelivered=true");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			existsSellerOrdersBean.setDomesticDelivered(true);
			Calendar orderPaidTimeBegin = getNow();
			orderPaidTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderPaidTimeEnd = getNow();
			orderPaidTimeEnd.add(Calendar.MONTH, -2);
			existsSellerOrdersBean
					.setOrderPaidTimeBegin(calendar2YMDString(orderPaidTimeBegin));
			existsSellerOrdersBean
					.setOrderPaidTimeEnd(calendar2YMDString(orderPaidTimeEnd));
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_006() {
		Logger.start(
				true,"卖家订单是否存在,只传SellerId, orderPaidTimeBegin,orderPaidTimeEnd,domesticDelivered=false");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			existsSellerOrdersBean.setDomesticDelivered(false);
			Calendar orderPaidTimeBegin = getNow();
			orderPaidTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderPaidTimeEnd = getNow();
			orderPaidTimeEnd.add(Calendar.MONTH, -2);
			existsSellerOrdersBean
					.setOrderPaidTimeBegin(calendar2YMDString(orderPaidTimeBegin));
			existsSellerOrdersBean
					.setOrderPaidTimeEnd(calendar2YMDString(orderPaidTimeEnd));
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_007() {
		Logger.start(true,"卖家订单是否存在,只传SellerId, orderCreatedTimeBegin,orderCreatedTimeEnd,orderID");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			existsSellerOrdersBean.setOrderId(105414161);
			Calendar orderCreatedTimeBegin = getNow();
			orderCreatedTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderCreatedTimeEnd = getNow();
			orderCreatedTimeEnd.add(Calendar.MONTH, -2);
			existsSellerOrdersBean
					.setOrderCreatedTimeBegin(calendar2YMDString(orderCreatedTimeBegin));
			existsSellerOrdersBean
					.setOrderCreatedTimeEnd(calendar2YMDString(orderCreatedTimeEnd));
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_008() {
		Logger.start(true,"卖家订单是否存在,只传SellerId, orderCreatedTimeBegin,orderCreatedTimeEnd,orderGroupId");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			existsSellerOrdersBean.setOrderGroupId(13913536);
			Calendar orderCreatedTimeBegin = getNow();
			orderCreatedTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderCreatedTimeEnd = getNow();
			existsSellerOrdersBean
					.setOrderCreatedTimeBegin(calendar2YMDString(orderCreatedTimeBegin));
			existsSellerOrdersBean
					.setOrderCreatedTimeEnd(calendar2YMDString(orderCreatedTimeEnd));
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_009() {
		Logger.start(
				true,"卖家订单是否存在,只传SellerId, orderCreatedTimeBegin,orderCreatedTimeEnd,orderRefund=true");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			existsSellerOrdersBean.setOrderRefund(true);
			Calendar orderCreatedTimeBegin = getNow();
			orderCreatedTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderCreatedTimeEnd = getNow();
			existsSellerOrdersBean
					.setOrderCreatedTimeBegin(calendar2YMDString(orderCreatedTimeBegin));
			existsSellerOrdersBean
					.setOrderCreatedTimeEnd(calendar2YMDString(orderCreatedTimeEnd));
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_010() {
		Logger.start(
				true,"卖家订单是否存在,只传SellerId, orderCreatedTimeBegin,orderCreatedTimeEnd,orderRefund=false");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			existsSellerOrdersBean.setOrderRefund(false);
			Calendar orderCreatedTimeBegin = getNow();
			orderCreatedTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderCreatedTimeEnd = getNow();
			existsSellerOrdersBean
					.setOrderCreatedTimeBegin(calendar2YMDString(orderCreatedTimeBegin));
			existsSellerOrdersBean
					.setOrderCreatedTimeEnd(calendar2YMDString(orderCreatedTimeEnd));
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_011() {
		Logger.start(true,"卖家订单是否存在,只传SellerId, orderCreatedTimeBegin,orderCreatedTimeEnd,buyerNickName");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			String buyerNickName = EnvSetup.getData("BuyUserName");
			existsSellerOrdersBean.setBuyerNickName(buyerNickName);
			Calendar orderCreatedTimeBegin = getNow();
			orderCreatedTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderCreatedTimeEnd = getNow();

			existsSellerOrdersBean
					.setOrderCreatedTimeBegin(calendar2YMDString(orderCreatedTimeBegin));
			existsSellerOrdersBean
					.setOrderCreatedTimeEnd(calendar2YMDString(orderCreatedTimeEnd));
			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ExistsSellerOrders_012() {
		Logger.start(true, "卖家订单是否存在,传多个参数1");
		try {
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			existsSellerOrdersBean.setSellerId(sellerId);
			existsSellerOrdersBean.setOrderRefund(false);
			existsSellerOrdersBean.setDomesticDelivered(true);
			Calendar orderCreatedTimeBegin = getNow();
			orderCreatedTimeBegin.add(Calendar.MONTH, -5);
			Calendar orderCreatedTimeEnd = getNow();

			Calendar orderPaidTimeBegin = getNow();
			orderPaidTimeBegin.add(Calendar.MONTH, -4);
			Calendar orderPaidTimeEnd = getNow();
			orderPaidTimeEnd.add(Calendar.MONTH, -1);
			existsSellerOrdersBean
					.setOrderCreatedTimeBegin(calendar2YMDString(orderCreatedTimeBegin));
			existsSellerOrdersBean
					.setOrderCreatedTimeEnd(calendar2YMDString(orderCreatedTimeEnd));
			existsSellerOrdersBean
					.setOrderPaidTimeBegin(calendar2YMDString(orderPaidTimeBegin));
			existsSellerOrdersBean
					.setOrderPaidTimeEnd(calendar2YMDString(orderPaidTimeEnd));

			existsSellerOrdersCall.setData(existsSellerOrdersBean);
			existsSellerOrdersCall.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

}